package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 分页查询动态的评论列表
     *   查询的表：comment
     *   参数：动态id（publishId），互动类型（commentType：1-点赞，2-评论，3-喜欢）
     */
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //1、调用API分页查询数据   List<comment>
        int commentType = 2;
        List<Comment> list = commentApi.findComments(page,pagesize,movementId,commentType);
        //2、判断评论list是否为空
        if(list == null || list.size()<=0) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);

        //3、一个comment对象转化成vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            //查询UserInfo
            UserInfo userInfo = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //保存评论
    public void saveComment(String movementId, String comment) {
        //1、创建互动对象
        Comment comment1  = new Comment();
        //2、补充属性
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setContent(comment);
        comment1.setCreated(System.currentTimeMillis());
        comment1.setUserId(UserHolder.getUserId());
        int commentType = 2;
        comment1.setCommentType(commentType);
        //3、调用API保存，获取此动态的评论数量
        Integer counts = commentApi.save(comment1);
        System.out.println("总评论数="+counts);
    }

    //点赞
    public Integer like(String movementId) {

        Long userId = UserHolder.getUserId();
        Integer commentType = 1;
        //1、查询是否已经点赞，如果已点赞抛出异常 （mongodb，redis）
        Boolean hashComment = commentApi.hasComment(movementId,userId,commentType); //动态id，用户id，操作类型
        if(hashComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //2、如果未点赞，构造Comment对象，保存数据（保存mongodb）
        Comment comment = new Comment();
        comment.setCommentType(commentType);
        comment.setPublishId(new ObjectId(movementId));
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(userId);
        Integer count = commentApi.save(comment);//需要修改
        //3、存入Redis中
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+userId;
        redisTemplate.opsForHash().put(key,hashKey,"1");

        //发送消息
        mqMessageService.sendLogMessage(userId,"0203","movement",movementId);
        return count;
    }

    /**
     * 取消点赞
     */
    public Integer dislike(String movementId) {
        //1、判断是否已经点赞
        Long userId = UserHolder.getUserId();
        Integer commentType = 1;
        //1、查询是否已经点赞，如果已点赞抛出异常 （mongodb，redis）
        Boolean hashComment = commentApi.hasComment(movementId,userId,commentType); //动态id，用户id，操作类型
        //2、如果未点赞，抛出异常
        if(!hashComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、如果已点赞，删除Mongodb数据
        Integer count = commentApi.delete(movementId,commentType,userId); //动态id，操作类型。用户id
        //4、删除redis中数据
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId; //redis的数据key
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+userId;  //hashkey
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
